/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.networking;

/**
 * Operation to post a new comment.
 */
public class NewCommentOperation extends NetworkOperation {

    /**
     * Listener interface
     */
    public interface Listener {

        /**
         * Returns the comment id of the new comment.
         * @param post
         * @param commentId
         */
        public void newCommentSent(Post post, String commentId);
    }
    private static final String WP_NEW_COMMENT = "wp.newComment";
    private Post post;
    private String content;
    private Listener listener;

    /**
     * Constructor
     * @param listener
     * @param post Parent post for the comment
     * @param content Comment content
     */
    public NewCommentOperation(Listener listener, Post post, String content) {
        this.listener = listener;
        this.post = post;
        this.content = content;
    }

    /**
     * Starts the operation
     */
    public void start() {
        Request req = new Request(WP_NEW_COMMENT);
        req.addStringParam(post.blog.blogId);
        req.addStringParam(post.blog.blogUser);
        req.addStringParam(post.blog.blogUserPassword);
        req.addStringParam(post.postId);
        //req.addStructMember("comment_parent", parent);
        req.addStructMember("content", content);
        Network nw = new Network(this);
        nw.startHttpPost(post.blog.xmlrpcUrl, req.request());
    }

    /**
     * Parses the server response and calls the listener.
     * @param response
     */
    public void networkHttpPostResponse(String response) {
        try {
            NewCommentParser handler = new NewCommentParser();
            parse(response, handler);
            listener.newCommentSent(post, handler.commentId);
        } catch (ParseError e) {
            listener.newCommentSent(post, null);
        }
    }
}
